package com.example.signupservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.commonservice.Common.Result;
import com.example.signupservice.entity.ActivityCheckin;
import com.example.signupservice.feign.ActivityFeignClient;
import com.example.signupservice.feign.UserFeignClient;
import com.example.signupservice.mapper.ActivityCheckinMapper;
import com.example.signupservice.service.ActivityCheckinService;
import com.example.signupservice.service.ActivitySignupService;
import com.example.signupservice.entity.ActivitySignup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class ActivityCheckinServiceImpl extends ServiceImpl<ActivityCheckinMapper, ActivityCheckin>
        implements ActivityCheckinService {

    @Autowired
    private ActivitySignupService signupService;
    @Autowired
    private ActivityFeignClient activityFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public IPage<ActivityCheckin> pageCheckins(Integer current, Integer size, Map<String, Object> params) {
        Page<ActivityCheckin> page = new Page<>(current, size);
        QueryWrapper<ActivityCheckin> wrapper = new QueryWrapper<>();

        if(params.containsKey("signupId") && params.get("signupId") != null) {
            wrapper.eq("signup_id", params.get("signupId"));
        }
        if(params.containsKey("operator") && params.get("operator") != null) {
            wrapper.eq("checkin_by", params.get("operator"))
                    .or()
                    .eq("checkout_by", params.get("operator"));
        }

        IPage<ActivityCheckin> result = page(page, wrapper);

        // 填充关联字段
        result.getRecords().forEach(checkin -> {
            ActivitySignup signup = signupService.getById(checkin.getSignupId());
            if (signup != null) {
                checkin.setVolunteerId(signup.getVolunteerId());
                checkin.setActivityId(signup.getActivityId());

                // 通过Feign获取活动名称
                Result<String> activityResult = activityFeignClient.getActivityName(signup.getActivityId());
                if(activityResult.isSuccess()) {
                    checkin.setActivityName(activityResult.getData());
                }

                // 通过Feign获取志愿者名称
                Result<String> volunteerResult = userFeignClient.getVolunteerName(signup.getVolunteerId());
                if(volunteerResult.isSuccess()) {
                    checkin.setVolunteerName(volunteerResult.getData());
                }
            }
        });

        return result;
    }

    @Override
    public ActivityCheckin getCheckinDetail(Long signupId) {
        ActivityCheckin checkin = lambdaQuery()
                .eq(ActivityCheckin::getSignupId, signupId)
                .one();

        if (checkin != null) {
            ActivitySignup signup = signupService.getById(signupId);
            if (signup != null) {
                checkin.setActivityName(signup.getActivityName());
                checkin.setVolunteerName(signup.getVolunteerName());
            }
        }

        return checkin;
    }

    @Override
    public ActivityCheckin getCheckinRecord(Long id) {
        ActivityCheckin checkin = getById(id);
        if (checkin != null) {
            // 1. 通过signupId获取报名记录
            ActivitySignup signup = signupService.getById(checkin.getSignupId());
            if (signup != null) {
                // 2. 设置volunteerId和activityId
                checkin.setVolunteerId(signup.getVolunteerId());
                checkin.setActivityId(signup.getActivityId());

                // 3. 通过Feign获取活动名称和志愿者名称
                Result<String> activityResult = activityFeignClient.getActivityName(signup.getActivityId());
                if(activityResult.isSuccess()) {
                    checkin.setActivityName(activityResult.getData());
                }

                Result<String> volunteerResult = userFeignClient.getVolunteerName(signup.getVolunteerId());
                if(volunteerResult.isSuccess()) {
                    checkin.setVolunteerName(volunteerResult.getData());
                }
            }
        }
        return checkin;
    }

    @Override
    public boolean addCheckinRecord(ActivityCheckin checkin) {
        // 设置创建时间
//        if (checkin.getCheckinTime() == null) {
//            checkin.setCheckinTime(LocalDateTime.now());
//        }
        return save(checkin);
    }
    @Override
    public boolean delete(Long signupId, Long volunteerId) {
        // 1. 查询关联的签到记录（注意：这里使用signupId查询，而不是主键id）
        ActivityCheckin checkin = lambdaQuery()
                .eq(ActivityCheckin::getSignupId, signupId)
                .one();

        // 2. 检查记录是否存在
        if (checkin == null) {
            return false; // 记录不存在
        }

        // 3. 通过signupId获取报名记录，验证志愿者ID

        if (!checkin.getVolunteerId().equals(volunteerId)) {
            return false; // 志愿者ID不匹配
        }

        // 6. 使用ActivityCheckin的主键id进行删除（修正了原代码的问题）
        return removeById(checkin.getId());
    }
    @Override
    public boolean deleteCheckinRecord(Long id) {
        return removeById(id);
    }

    @Override
    public boolean updateCheckinRecord(ActivityCheckin checkin) {
        return updateById(checkin);
    }

    @Override
    public boolean checkin(Long signupId, Long operator) {
        // 检查是否已签到
        ActivityCheckin checkin = lambdaQuery()
                .eq(ActivityCheckin::getSignupId, signupId)
                .one();

        if (checkin != null) {
            if (checkin.getCheckinTime() != null) {
                return false; // 已签到
            }
            // 更新签到信息
            checkin.setCheckinTime(LocalDateTime.now());
            checkin.setCheckinBy(operator);
            return updateById(checkin);
        } else {
            // 创建新的签到记录
            checkin = new ActivityCheckin();
            checkin.setSignupId(signupId);
            checkin.setCheckinTime(LocalDateTime.now());
            checkin.setCheckinBy(operator);
            return save(checkin);
        }
    }

    @Override
    public boolean checkout(Long signupId, Long operator) {
        // 检查是否已签到
        ActivityCheckin checkin = lambdaQuery()
                .eq(ActivityCheckin::getSignupId, signupId)
                .one();

        if (checkin == null || checkin.getCheckinTime() == null) {
            return false; // 未签到，无法签退
        }

        if (checkin.getCheckoutTime() != null) {
            return false; // 已签退
        }

        // 更新签退信息
        checkin.setCheckoutTime(LocalDateTime.now());
        checkin.setCheckoutBy(operator);
        return updateById(checkin);
    }

    @Override
    public boolean updateEvaluation(Long checkinId, Integer score, String comment) {
        ActivityCheckin checkin = getById(checkinId);
        if (checkin == null) {
            return false;
        }

        checkin.setScore(score);
        checkin.setComment(comment);
        return updateById(checkin);
    }
}
